package com.zm.system.exception;

import com.zm.common.constants.ResultCode;
import com.zm.system.web.entity.vo.AjaxResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.http.converter.HttpMessageConversionException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

@RestControllerAdvice
@Slf4j
public class ApiExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    public AjaxResult exception(Exception e) {
        log.error("Exception:{}", e.getLocalizedMessage());
        e.printStackTrace();
        return AjaxResult.error(ResultCode.ERROR);
    }

    /**
     * 处理自定义异常
     *
     * @Author: 汪焰
     * @Date: 2020/6/14 20:10
     * version 1.0.0
     **/
    @ExceptionHandler(value = ApiException.class)
    public AjaxResult apiException(ApiException e) {
        log.error("Exception:{}", e.getMsg());
        return AjaxResult.error(e.getCode(), e.getMsg());
    }

    @ExceptionHandler(UnauthorizedException.class)
    public AjaxResult unauthorizedException(UnauthorizedException e) {
        log.error("没有权限访问该资源 ：{}", e.getLocalizedMessage());
        return AjaxResult.error(ResultCode.ACCOUNT_NOT_PERMISSION);
    }

    /**
     * 处理 参数校验异常 Http消息转换异常
     */
    @ExceptionHandler(value = HttpMessageConversionException.class)
    public AjaxResult httpMessageNotReadableExceptionHandler(HttpMessageConversionException e) {
        log.error("请求参数解析异常 ：{}", e.getLocalizedMessage());
        return AjaxResult.error(ResultCode.DATA_ERROR.getCode(), ResultCode.DATA_ERROR.getMsg() + ":" + e.getLocalizedMessage());
    }

    /**
     * 处理 参数校验异常 处理validation
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public AjaxResult methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        log.error("params error():{},exception:{}", e.getBindingResult().getAllErrors(), e);
        List<ObjectError> errors = e.getBindingResult().getAllErrors();
        return createValidExceptionResp(errors);
    }

    private AjaxResult createValidExceptionResp(List<ObjectError> errors) {
        String[] msgs = new String[errors.size()];
        int i = 0;
        for (ObjectError error : errors) {
            msgs[i] = error.getDefaultMessage();
            log.info("msg={}", msgs[i]);
            i++;
        }
        return AjaxResult.error(ResultCode.DATA_ERROR.getCode(), ResultCode.DATA_ERROR.getMsg() + ":" + msgs[0]);
    }


}
